#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
版本管理对话框
"""

from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QLabel,
    QListWidget, QTextEdit, QMessageBox, QLineEdit, QGroupBox,
    QSplitter, QListWidgetItem
)
from PyQt5.QtCore import Qt
from typing import Optional
from version_manager import GitVersionManager


class VersionManagerDialog(QDialog):
    """版本管理对话框"""
    
    def __init__(self, parent, manager: GitVersionManager):
        """
        初始化对话框
        
        Args:
            parent: 父窗口
            manager: Git 版本管理器
        """
        super().__init__(parent)
        self.manager = manager
        self.setWindowTitle("版本管理")
        self.setMinimumSize(800, 600)
        self.setup_ui()
        self.refresh_versions()
    
    def setup_ui(self):
        """设置 UI"""
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 顶部按钮
        top_layout = QHBoxLayout()
        
        refresh_btn = QPushButton("🔄 刷新")
        refresh_btn.clicked.connect(self.refresh_versions)
        top_layout.addWidget(refresh_btn)
        
        create_btn = QPushButton("➕ 创建版本")
        create_btn.clicked.connect(self.create_version)
        top_layout.addWidget(create_btn)
        
        checkout_btn = QPushButton("↩️ 回滚到此版本")
        checkout_btn.clicked.connect(self.checkout_version)
        top_layout.addWidget(checkout_btn)
        
        top_layout.addStretch()
        
        # 当前版本标签
        self.current_version_label = QLabel("当前版本: 未知")
        top_layout.addWidget(self.current_version_label)
        
        layout.addLayout(top_layout)
        
        # 分割器
        splitter = QSplitter(Qt.Horizontal)
        
        # 左侧：版本列表
        left_widget = QGroupBox("版本列表")
        left_layout = QVBoxLayout()
        
        self.version_list = QListWidget()
        self.version_list.itemSelectionChanged.connect(self.on_version_selected)
        self.version_list.itemDoubleClicked.connect(self.show_version_details)
        left_layout.addWidget(self.version_list)
        
        left_widget.setLayout(left_layout)
        splitter.addWidget(left_widget)
        
        # 右侧：版本详情
        right_widget = QGroupBox("版本详情")
        right_layout = QVBoxLayout()
        
        self.detail_text = QTextEdit()
        self.detail_text.setReadOnly(True)
        right_layout.addWidget(self.detail_text)
        
        right_widget.setLayout(right_layout)
        splitter.addWidget(right_widget)
        
        splitter.setStretchFactor(0, 1)
        splitter.setStretchFactor(1, 2)
        
        layout.addWidget(splitter)
        
        # 底部按钮
        bottom_layout = QHBoxLayout()
        bottom_layout.addStretch()
        
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        bottom_layout.addWidget(close_btn)
        
        layout.addLayout(bottom_layout)
    
    def refresh_versions(self):
        """刷新版本列表"""
        self.version_list.clear()
        
        # 获取当前版本
        current_version = self.manager.get_current_version()
        if current_version:
            self.current_version_label.setText(f"当前版本: {current_version}")
        else:
            self.current_version_label.setText("当前版本: 未初始化")
        
        # 获取版本列表
        versions = self.manager.list_versions()
        
        for version in versions:
            item_text = f"{version['hash']} - {version['date']} - {version['message']}"
            item = QListWidgetItem(item_text)
            item.setData(Qt.UserRole, version)
            
            # 标记当前版本
            if current_version and version['hash'] == current_version:
                item.setText(f"★ {item_text}")
                item.setForeground(Qt.blue)
            
            self.version_list.addItem(item)
        
        if not versions:
            self.version_list.addItem("暂无版本")
    
    def on_version_selected(self):
        """版本选择变化"""
        items = self.version_list.selectedItems()
        if not items:
            self.detail_text.clear()
            return
        
        item = items[0]
        version = item.data(Qt.UserRole)
        
        if not version:
            return
        
        # 获取版本详细信息
        version_info = self.manager.get_version_info(version['full_hash'])
        
        if version_info:
            detail_text = f"""
版本信息
========

Hash: {version_info['hash']}
完整 Hash: {version_info['full_hash']}
日期: {version_info['date']}
作者: {version_info['author']} <{version_info['email']}>
描述: {version_info['message']}

修改的文件:
{chr(10).join(f'  - {f}' for f in version_info['files'])}

统计信息:
{version_info['stats']}
"""
            self.detail_text.setText(detail_text)
        else:
            self.detail_text.setText(f"无法获取版本信息: {version['hash']}")
    
    def show_version_details(self, item: QListWidgetItem):
        """显示版本详情（双击）"""
        version = item.data(Qt.UserRole)
        if not version:
            return
        
        version_info = self.manager.get_version_info(version['full_hash'])
        if not version_info:
            QMessageBox.warning(self, "错误", "无法获取版本信息")
            return
        
        # 创建详情对话框
        detail_dialog = QDialog(self)
        detail_dialog.setWindowTitle(f"版本详情: {version['hash']}")
        detail_dialog.setMinimumSize(600, 400)
        
        layout = QVBoxLayout()
        detail_dialog.setLayout(layout)
        
        detail_text = QTextEdit()
        detail_text.setReadOnly(True)
        detail_text.setText(f"""
版本信息
========

Hash: {version_info['hash']}
完整 Hash: {version_info['full_hash']}
日期: {version_info['date']}
作者: {version_info['author']} <{version_info['email']}>
描述: {version_info['message']}

修改的文件:
{chr(10).join(f'  - {f}' for f in version_info['files'])}

统计信息:
{version_info['stats']}
""")
        layout.addWidget(detail_text)
        
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(detail_dialog.accept)
        layout.addWidget(close_btn)
        
        detail_dialog.exec_()
    
    def create_version(self):
        """创建新版本"""
        from datetime import datetime
        
        description, ok = QMessageBox.getText(
            self,
            "创建版本",
            "请输入版本描述（可选）：",
            QLineEdit.Normal,
            f"Update: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        )
        
        if not ok:
            return
        
        success, message, version_hash = self.manager.create_version(description)
        
        if success:
            QMessageBox.information(
                self,
                "成功",
                f"{message}\n版本ID: {version_hash}"
            )
            self.refresh_versions()
        else:
            QMessageBox.warning(
                self,
                "失败",
                message
            )
    
    def checkout_version(self):
        """回滚到选中版本"""
        items = self.version_list.selectedItems()
        if not items:
            QMessageBox.warning(self, "提示", "请先选择一个版本")
            return
        
        item = items[0]
        version = item.data(Qt.UserRole)
        
        if not version:
            return
        
        reply = QMessageBox.question(
            self,
            "确认",
            f"确定要回滚到版本 {version['hash']} 吗？\n"
            f"描述: {version['message']}\n\n"
            "注意：这将覆盖当前的标注文件！",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply != QMessageBox.Yes:
            return
        
        success, message = self.manager.checkout_version(version['full_hash'])
        
        if success:
            QMessageBox.information(self, "成功", message)
            self.refresh_versions()
        else:
            QMessageBox.warning(self, "失败", message)

